#winscp的xml日志分析，并邮件通知收件人的python代码
import xml.etree.ElementTree as ET
from xml.etree.ElementTree import Element
import smtplib
from email.mime.text import MIMEText
import sys
import os,time
import logging




def external_email():
#外部邮件的发送方法
    import smtplib
    from email.header import Header
    from email.mime.text import MIMEText
    mail_host = "smtp.163.com"      # SMTP服务器
    mail_user = "18970078166"                  # 用户名wjb711
    mail_pass = "xxx"               # 授权密码，非登录密码

    sender = '18970078166@163.com'    # 发件人邮箱(最好写全, 不然会失败)
    receivers = ['18970078166@163.com','10054053@qq.com']  # 接收邮件，可设置为你的QQ邮箱或者其他 邮箱

    #title ='hello'
    #global content
    #print ('content is:',content,type(content))
    #content="this is for test"
    message = MIMEText(content, 'plain',"utf-8")  # 内容, 格式, 编码
    message['From'] = "{}".format(sender)
    message['To'] = ",".join(receivers)
    message['Subject'] = title
    message['content_type']='html'

    try:
        smtpObj = smtplib.SMTP_SSL(mail_host, 465)  # 启用SSL发信, 端口一般是465
        smtpObj.login(mail_user, mail_pass)  # 登录验证
        smtpObj.sendmail(sender, receivers, message.as_string())  # 发送
        print("mail has been send successfully.")
    except smtplib.SMTPException as e:
        print(e)

def internal_email():
#内部邮件的发送方法
    import smtplib
    #from email.mime.multipart import MIMEMultipart
    from email.mime.text import MIMEText
    #print ('hello')

    smtp = smtplib.SMTP()
    smtp.connect('10.4.172.3')
    #smtp.login(username, password)
    #msg = MIMEMultipart('mixed')
    #global content
    sender='jianbo.wang@gi-de.com'
    msg = MIMEText(content, 'plain', 'utf-8')
    msg['Subject'] = title
    msg['content_type']='html'
    smtp.sendmail(sender, receivers, msg.as_string())
    smtp.quit()
    #print ('ok',email_address,'ok1')

def xml_analysis(file):
#xml的分析函数
    tree=ET.parse(file)
    root=tree.getroot()
    result=[]
    for child in root:
        #print(child.items)
        if 'touch' in child.tag:
            #pass
            #print(child[0].attrib['value'])
            result.append(child[0].attrib['value'])
    return result



    

if __name__=='__main__':
    #定义xml日志所在文件夹
    log_folder='C:\\Users\\xxx\\Desktop\\551\\log\\xml\\'
    #定义日志修改的时间（分钟）
    limit_time=100000
    #邮件提醒给谁
    receivers=['xxx@xxx.com']
    #邮件标题
    title='上传给客户的文件'
    #内网邮件0还是外网邮件1
    mode=0
    #定义程序日志记录
    logging.basicConfig(filename="newfile.log",
                    format='%(asctime)s %(message)s',
                    filemode='a')
    # Creating an object
    logger = logging.getLogger()
     
    # Setting the threshold of logger to DEBUG
    logger.setLevel(logging.DEBUG)
    result=[]
    for file in os.listdir(log_folder):
        if file.endswith('xml'):
            if(time.time()-os.path.getmtime(log_folder+file))/60<limit_time:
                #print(log_folder+file)
                for item in xml_analysis(log_folder+file):
                    #print(item)
                    result.append(item)
    #print('*********************')
    for item in result:
        print(item)
    #如果有结果，发送邮件
    if result:
        #邮件正文
        content='\n'.join(result)
        
        
        if mode==0:
            internal_email()
        else:
            external_email()
        logger.warning('运行完成，'+''.join(result))
    else:
        logger.warning('运行完成，无内容变更')
    print('end')